# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'S1195': {
        #  爽快支付 支付宝WAP 2.6% 200-10000 dwc
        'API_KEY': 'e059618ea2f1d257dc201ce5c0092aa1',
        'gateway': 'https://api.d3cq.com/api/order/pay',
        'query_gateway': 'https://api.d3cq.com/api/order/get',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s = s[0:-1]
    s += '@@%s' % key
    _LOGGER.info("coolpay sing string : %s", s)
    return _gen_sign(s)


def generate_notify_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s = s[0:-1]
    s += '%s' % key
    _LOGGER.info("coolpay sing string : %s", s)
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("coolpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("coolpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '219.135.56.195'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('sid', app_id),
        ('amount', str(pay_amount)),
        ('outTradeNo', str(pay.id)),
        ('orderType', 1),
        ('notifyUrl', '{}/pay/api/{}/coolpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("coolpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['outTradeNo'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("coolpay create rsp data: %s %s", response.status_code, response.text)
    data = json.loads(response.text)['data']
    return {'charge_info': data['payUrl']}


# D0商户异步通道
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("coolpay notify data: %s, order_id is: %s", data, data['out_trade_no'])
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('coolpay event does not contain pay ID')
    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)
    mch_id = pay.mch_id
    trade_status = str(data['code'])
    trade_no = data['trade_no']
    total_fee = float(data['total_amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 系统仅支付成功的订单下发通知，其它状态不下发
    if trade_status == 'success':
        _LOGGER.info('coolpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('sid', app_id),
        ('tradeNo', pay_order.third_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("coolpay query data:%s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("coolpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        trade_status = str(data['status'])
        trade_no = str(data['tradeNo'])
        total_fee = float(data['amount'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 订单状态（10:已出码待支付,11:未支付,12:支付成功,其它:未出码）
        if trade_status == '12':
            _LOGGER.info('coolpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('coolpay data error, status_code: %s', response.status_code)
